package com.xhu.service.impl;

import com.xhu.service.DecodeService;
import com.xhu.util.*;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Base64;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class DecodeServiceImpl implements DecodeService {
    @Override
    public String decode(String totalPath, String type) throws IOException {
        //读取带有嵌入信息的html文件
        List<StringBuilder> context = null;
        context = HideHtml.getHtmlContents(totalPath, false);
        String binBase64 = "false";
        if (type.equals("0")){
            //根据内容生成解码对象
            Hider hider = new Hider(context);
            //获取解析出来的二进制字符串
            binBase64 = hider.deCode(type);
        }else{
            binBase64 = this.getBinBase64(context);
        }


        if (binBase64.equals("false")){
            return binBase64;
        }
        //将二进制字符串反向转化为base64字符串
        String Base64 = BinaryStringConverteUtil.toString(binBase64);
        //将base64字符串解密成最终字符串
        byte[] base64decodedBytes = java.util.Base64.getDecoder().decode(Base64);
        String content = new String(base64decodedBytes, "utf-8");

        content = DESUtil.decrypt(HideHtml.DESPSW, content);
        return content;
    }

    private String getBinBase64(List<StringBuilder> context){
        StringBuilder builder = new StringBuilder();
        for (StringBuilder htmlContent : context) {
            //正则表达式匹配属性值
            String reg = "(?<=[a-z|\\-|_]=)['|\"].+?['|\"]";
            Pattern p = Pattern.compile(reg);
            Matcher m = p.matcher(htmlContent);
            while (m.find()) {
                String attr = m.group();

                if (Utils.letterSum(attr) % 2 == 0) {
                    builder.append('0');
                } else {
                    builder.append('1');
                }

                if (Utils.IsCaptail(attr)) {
                    builder.append('0');
                } else {
                    builder.append('1');
                }
            }
        }
        String type = builder.substring(0,2);
        if (!type.equals("01")){
            return "false";
        }

        String lens = builder.substring(2,2+HideHtml.LEN);
        int len = Integer.parseInt(lens.toString(), 2);

        String result= builder.substring(2+HideHtml.LEN,2+HideHtml.LEN+len);
        System.out.println(result);
        return result;
    }
}


